<template>
  <div class>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="pagBox">
      <!-- 步骤条 -->
      <el-steps :active="activeName-0" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 添加商品的表单，包裹选项卡 -->
      <el-form :model="addForm" :rules="addGoodsRules" ref="addGoodsRuleForm" label-width="100px">
        <!-- 纵向tab栏 -->
        <el-tabs
          v-model="activeName"
          tab-position="left"
          class="pagBox"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <!-- 第一个tab -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" class="t-left">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 第二个tab -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" :key="item.attr_id" v-for="item in manyTableData">
              <!-- 使用数组渲染复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="val" v-for="(val,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 第三个tab -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
              label-width="150"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 
              upload文件上传组件 
              action 图片提交的接口地址
              on-preview 预览
              on-remove 删除
              file-list 定义文件夹
              list-type 文件类型
              :headers ：设置上传图片的请求头
            -->
            <el-upload
              :action="urlPath"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
              :headers="headerObj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
          </el-tab-pane>
          <el-tab-pane label="完成" name="5">
            <el-button type="primary" @click="submitGoods">确定新增商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 预览图片弹窗 -->
    <el-dialog :visible.sync="previewVisible" width="50%" >
      <img :src="previewPath" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      // 当前索引页面
      // currentIndex: 0,
      activeName: "0",
      // 表单基本信息
      addForm: {
        goods_name: "abc",
        goods_price: 1,
        goods_number: 1,
        goods_weight: 1,
        // 发请求的时候这里要发字符串
        goods_cat: [1, 3, 6],
        // 参数和属性
        attrs: [],
        // 把获取到的临时地址存到tmp_path
        pics: [],
        // 富文本编辑器的数据
        goods_introduce:'',
      },
      // 上传图片请求路径
      urlPath: "http://127.0.0.1:8888/api/private/v1/upload",
      // 上传图片请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 预览图片的地址
      previewPath:'',
      // 预览图片弹窗
      previewVisible:false,
      // 级联菜单数据源
      cateList: [],
      // 级联菜单配置项
      cateProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        expandTrigger: "hover",
      },
      // 表单基本信息规则
      addGoodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
      },
      // 参数数据
      manyTableData: [],
      // 属性数据
      onlyTableData: [],
    };
  },
  created() {
    this.getCateList();
  },
  mounted() {},
  watch: {},
  computed: {
    cateId() {
      return this.addForm.goods_cat[this.addForm.goods_cat.length - 1];
    },
  },
  methods: {
    // 获取分类数据
    getCateList() {
      this.$axios.get("categories").then((val) => {
        // console.log(val);
        this.cateList = val.data;
      });
    },
    // 级联菜单点选时
    handleChange() {
      console.log(this.addForm.goods_cat);
    },
    // 点击离开tab栏之前
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName == "0") {
        if (this.addForm.goods_cat.length != 3) {
          this.$message.error("请先选择商品分类!");
          return false;
        }
        if (this.addForm.goods_name.trim() == "") {
          this.$message.error("请填写商品名称!");
          return false;
        }
        if (this.addForm.goods_price == 0) {
          this.$message.error("请填写商品价格!");
          return false;
        }
        if (this.addForm.goods_weight == 0) {
          this.$message.error("请填写商品重量!");
          return false;
        }
        if (this.addForm.goods_number == 0) {
          this.$message.error("请填写商品数量!");
          return false;
        }
      }
      // console.log(activeName,oldActiveName);
    },
    // 点击tab栏时
    tabClicked() {
      if (this.activeName == "1") {
        this.$axios
          .get("categories/" + this.cateId + "/attributes", {
            params: { sel: "many" },
          })
          .then((val) => {
            console.log(val);
            val.data.forEach((item) => {
              item.attr_vals = item.attr_vals.trim().split(" ");
            });
            // 判断是否拿到
            this.manyTableData = val.data;
          });
      } else if (this.activeName == "2") {
        this.$axios
          .get("categories/" + this.cateId + "/attributes", {
            params: { sel: "only" },
          })
          .then((val) => {
            console.log(val);
            // 判断是否拿到
            this.onlyTableData = val.data;
          });
      }
    },

    // 提交商品
    submitGoods() {
      this.addForm.goods_cat = this.addForm.goods_cat.join(",");

      // 处理动态参数
      console.log(this.manyTableData);
      this.manyTableData.forEach((item) => {
        let temp = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(" "),
        };
        this.addForm.attrs.push(temp);
      });

      // 处理静态属性
      console.log(this.onlyTableData);
      this.onlyTableData.forEach((item) => {
        let temp = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals,
        };
        this.addForm.attrs.push(temp);
      });

      // 发送添加商品请求i之后
      this.$axios.post("goods", this.addForm).then((val) => {
        console.log(val);
        if (val.meta.status != 201) {
          return this.$message.error(val.meta.msg);
        }
        this.$message.success(val.meta.msg);
        this.$router.push("/goods");
      });
    },

    // 处理图片预览
    handlePreview(file) {
      console.log(file);
      this.previewVisible=true;
      this.previewPath=file.response.data.url;
    },

    // 处理图片删除
    handleRemove(file) {
      // console.log(file);
      let delPath = file.response.data.tmp_path;
      let index = this.addForm.pics.findIndex((item) => {
        return item.pic == delPath;
      });
      this.addForm.pics.splice(index, 1);
    },

    // 处理图片添加成功
    handleSuccess(res) {
      // console.log(res);
      this.addForm.pics.push({
        pic: res.data.tmp_path,
      });
    },
  },
};
</script>
<style lang="css" scoped>
.el-tab-pane {
  border: 1px solid #eee;
  padding: 20px;
  box-sizing: border-box;
}
</style>